package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法就放行，比如跨域验证请求、静态资源等不需要身份校验的请求
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取请求的路径
        String requestURI = request.getRequestURI();
        log.info("拦截小程序请求路径接口={}",requestURI);

        String token = request.getHeader(Constants.USER_TOKEN);
        if(ObjectUtil.isEmpty(token)){
            //未登录
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(jwtProperties.getBase64EncodedSecretKey(), token);

        if (ObjectUtil.isEmpty(claims)) {
            //未登录
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
            //解析成功，获取登录的微信用户的ID
            String userId = claims.get(Constants.JWT_USERID).toString();
//            //创建本次请求的线程对象
//            ThreadLocal<Long> threadLocal = new ThreadLocal<>();
            //将登录的微信用户Id存入当前请求线程中
            UserThreadLocal.set(Long.valueOf(userId));
            return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应结束，需清理ThreadLocal中的数据，防止内存泄漏
        UserThreadLocal.remove();
    }
}
